#define MY_ID 1

#define BAUD 9600
#include <util/setbaud.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <util/delay.h>

#include "led.h"
#include "packet.h"

FUSES = 
{
	.low = (FUSE_CKSEL0 & FUSE_CKSEL1 & FUSE_CKSEL3 & FUSE_SUT0),
	.high = (FUSE_EESAVE & FUSE_SPIEN),
	.extended = EFUSE_DEFAULT,
};

ISR(USART_RX_vect)
{
	char c = UDR;
	
	if(bit_is_clear(UCSRA, FE))
		handlebyte(c);
}

void control(void)
{
	if(haspacket && (cmd.id == MY_ID))
	{
		switch(cmd.cmd)
		{
			case CMD_REPORT_ID:
				transmitbyte(MY_ID);
				break;
			case CMD_SET_ABS:
				set_color(cmd.rgb_color);
				break;
			case CMD_SET_FADE:
				fade_to_color(cmd.rgb_color, cmd.val);
				break;
			case CMD_SET_BLINK:
				blink_color(cmd.rgb_color, cmd.val);
				break;
			default:
				break;
		}
	}
}

void init(void)
{
	// IO
	DDRA = 0;
	DDRB = _BV(PB2) | _BV(PB3) | _BV(PB4);
	DDRD = _BV(PD5);
	
	PORTA = 0;
	PORTB = 0;
	PORTD = 0;
	
	//Timers
	TCCR0A = _BV(COM0A1) | 3; 
	TCCR0B = 1;
	OCR0A = 0;
	OCR0B = 0;
	
	TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
	TCCR1B = _BV(WGM12) | 1;
	
	OCR1A = 0;
	OCR1B = 0;
	
	//USART
	UCSRA = 0;
	UCSRB = _BV(RXEN) | _BV(RXCIE);
	UCSRC = 6;
	
	UBRRH = UBRRH_VALUE;
	UBRRL = UBRRL_VALUE;
	#if USE_2X
	UCSRA |= (1 << U2X);
	#else
	UCSRA &= ~(1 << U2X);
	#endif
}

int main(void)
{
	init();
	
	sei();
	
	while(1)
		control();
	
	return 0;
}
